<!--
 * @Author: tenet 18742176629@163.com
 * @Date: 2024/7/30 下午6:51
 * @LastEditors: tenet 18742176629@163.com
 * @LastEditTime: 2024/7/30 下午6:51
 * @FilePath: G:/token-for-token-front-admin/src/views/chainConfig\index.vue
 * @Description: Descri1ption
-->
<template>
  <Header>
    <template #title>{{ t('title.ChainInfoConfig') }}</template>
  </Header>
  <div class="generate">
    <el-button type="primary" @click="handleClick('add')">{{ t('chainConfig.ChainAdd') }}</el-button>
  </div>

  <!--  用户钱包配置 dialog -->
  <el-dialog v-model="isDialog" :title="dialogText" width="800" center @close="resetForm">
    <el-form :model="form" :rules="rules" ref="ruleRef" label-width="auto" style="max-width: 800px" label-position="top">
      <el-row style="width: 100%; display: flex; justify-content: space-between; align-items: center" >
        <el-form-item prop="chainConfigId0" :label="t('chainConfig.SellChain')" style="width: 48%">
          <el-select v-model.trim="form.chainConfigId0" :loading="loading" :placeholder="t('global.SelectChain')" @change="getChainTokensFun(form.chainConfigId0),sameChain(form.chainConfigId0, form.chainConfigId1)">
            <el-option v-for="(item, key) in chainList" :key="key" :label="item.chainName" :value="item.id"/>
          </el-select>
        </el-form-item>
        <el-form-item prop="token0" :label="t('chainConfig.SellToken')" style="width: 48%">
          <el-select v-model.trim="form.token0" :loading="loading" :placeholder="t('global.SelectToken')">
            <el-option v-for="(item, key) in tokenList" :key="key" :label="item.name" :value="item.id"/>
          </el-select>
        </el-form-item>
      </el-row>

      <el-row style="width: 100%; display: flex; justify-content: space-between; align-items: center" >
        <el-form-item prop="chainConfigId1" :label="t('chainConfig.BuyChain')" style="width: 48%">
          <el-select v-model.trim="form.chainConfigId1" :loading="loading" :placeholder="t('global.SelectChain')" @change="getChainTokensFun(form.chainConfigId1),sameChain(form.chainConfigId0, form.chainConfigId1)">
            <el-option v-for="(item, key) in chainList" :key="key" :label="item.chainName" :value="item.id"/>
          </el-select>
        </el-form-item>
        <el-form-item prop="token1" :label="t('chainConfig.BuyToken')" style="width: 48%" >
          <el-select v-model.trim="form.token1" :loading="loading" :placeholder="t('global.SelectToken')">
            <el-option v-for="(item, key) in tokenList" :key="key" :label="item.name" :value="item.id"/>
          </el-select>
        </el-form-item>
      </el-row>

      <el-form-item prop="rate" :label="t('chainConfig.Rate')">
        <el-input v-model.trim="form.rate" type="text" :placeholder="t('message.EnterRate')"/>
      </el-form-item>
    </el-form>
    <template #footer>
      <div class="dialog-footer">
        <el-button type="primary" @click="onSubmit" :loading="loading">{{ t('global.Submit') }}</el-button>
      </div>
    </template>
  </el-dialog>


  <div class="table">
    <el-table :data="tableData" border style="width: auto; height: 700px" v-loading="loading">
      <el-table-column prop="chainName0" :label="t('table.ChainName')" width="auto" align="center"/>
<!--      <el-table-column prop="chainConfigId0" :label="t('table.ChainName')" width="auto" align="center"/>-->
<!--      <el-table-column prop="symbol0" :label="t('table.ChainName')" width="auto" align="center"/>-->
      <el-table-column prop="token0" :label="t('table.Symbol')" width="auto" align="center"/>

      <el-table-column prop="" label="兑换方向" width="auto" align="center"> → </el-table-column>

      <el-table-column prop="chainName1" :label="t('table.ChainName')" width="auto" align="center"/>
<!--      <el-table-column prop="chainConfigId1" :label="t('table.ChainName')" width="auto" align="center"/>-->
<!--      <el-table-column prop="symbol1" :label="t('table.ChainName')" width="auto" align="center"/>-->
      <el-table-column prop="token1" :label="t('table.Symbol')" width="auto" align="center"/>


      <el-table-column prop="rate" :label="t('chainConfig.Rate')" width="auto" align="center"/>



      <el-table-column fixed="right" :label="t('global.Operation')" width="150" align="center">
        <template #default="scope">
          <el-button link type="primary" size="small" @click="handleClick('update',scope)">{{ t('global.Update') }}</el-button>
          <!--           <el-button link type="danger" size="small" @click="handleClick('delete',scope)">{{ t('global.Delete') }}</el-button>-->
          <el-popconfirm :title="t('message.DeleteTips')" @confirm="confirmSubmit(scope)">
            <template #reference>
              <el-button link type="danger" size="small">{{ t('global.Delete') }}</el-button>
            </template>
          </el-popconfirm>
        </template>
      </el-table-column>
    </el-table>
  </div>

  <div class="page">
    <el-pagination v-model:current-page="pageIndex" :page-size="pageSize" layout="total, prev, pager, next"
                   :total="total" @size-change="handleSizeChange" @current-change="handleCurrentChange"/>
  </div>
</template>

<script setup>
import {onMounted, reactive, ref, unref} from 'vue'
import {ElMessage, ElPagination, ElTable} from 'element-plus'
import Header from "../layout/header.vue";
import {useUserStore} from "@/stores"
import { chainConfigs, createChain, updateChain, findChain, deleteChain, chainTokens} from '@/require/api.js'
import {useI18n} from "vue-i18n";
import {formatTimestamp} from "@/utils/timeStamp.js";

const {t} = useI18n();
const userStore = useUserStore();

// 在组件被挂载后执行
onMounted(() => {
  getChainConfigs() // 获取配置 - 链列表
  getChainTokensFun() // 获取token列表
  getList();
});


const pageSize = ref(10)
const pageIndex = ref(1)
const total = ref(0)
const chainList = ref([]) // 配置列表 - 链
const tokenList = ref([]) // 配置列表 - token
const tableData = ref([])
const loading = ref(false)
const btnType = ref(); // 按钮类型
const dialogText = ref(t('chainConfig.ConfigAdd')) // dialog标题
const isDialog = ref(false) // 控制 dialog
const userId = ref(userStore.getUserInfo.userId)


const ruleRef = ref(null)


// form
const form = reactive({
  id: '',
  userId: '',
  chainName0: '', //卖出链
  chainConfigId0: '',  // 卖出链Id
  token0: '', // 卖出币种

  chainName1: '', // 买入链
  chainConfigId1: '',  // 买入链Id
  token1: '', // 买入币种

  rate: '' // 利率
})


// 点击按钮事件
async function handleClick(type, scope) {
  try {
    btnType.value = type;
    isDialog.value = true;
    if(btnType.value === 'add'){
      //  新增按钮
      dialogText.value = t('chainConfig.ChainAdd')

    }else if(btnType.value === 'update'){
      //  修改按钮
      dialogText.value = t('chainConfig.ChainEdit')

      form.userId = userId.value

      form.id = scope.row.id
      form.chainConfigId0 = scope.row.chainConfigId0
      form.chainConfigId1 = scope.row.chainConfigId1
      form.token0 = scope.row.token0
      form.token1 = scope.row.token1
      form.rate = scope.row.rate
    }
  }catch (e) {
    console.log(e)
  }
}


// 提交表单
async function onSubmit(){
  try {
    loading.value = true
    if(btnType.value === 'add'){
      await sameChain()
      const { code, data, msg } = await createChain({
        userId: userId.value,
        chainConfigId0: form.chainConfigId0,
        chainConfigId1: form.chainConfigId1,
        token0: form.token0,
        token1: form.token1,
        rate: form.rate,
      })
      if(code === 200){
        ElMessage.success(t('message.AddSuccess'))
      }else{
        ElMessage.error(msg)
      }
    }else if( btnType.value === 'update'){
      const { code, data, msg } = await updateChain({
        id: form.id,
        userId: userId.value,
        chainConfigId0: form.chainConfigId0,
        chainConfigId1: form.chainConfigId1,
        token0: form.token0,
        token1: form.token1,
        rate: form.rate
      })
      if(code === 200){
        ElMessage.success(t('message.AddSuccess'))
      }else{
        ElMessage.error(msg)
      }
    }
  }catch (e) {
    console.log(e)
  } finally {
    await resetForm()
    await getList()
    loading.value = false
    isDialog.value = false
  }
}



// 删除数据方法
async function confirmSubmit(scope){
  try {
    const { code, data, msg } = await deleteChain( {
      id: scope.row.id
    } )
    if(code === 200){
      ElMessage.success(t('message.DeleteSuccess'))
    }else{
      ElMessage.error(msg)
    }
  } catch (e) {
    console.log(e)
  } finally {
    await getList()
  }
}


// 表单验证规则
const rules = reactive({
  chainConfigId0: [
    {required: true, message: t('message.ChainNameNotNull'), trigger: 'blur'},
  ],
  chainConfigId1: [
    {required: true, message: t('message.ChainNameNotNull'), trigger: 'blur'},
  ],
  token0: [
    {required: true, message: t('message.ChainNameNotNull'), trigger: 'blur'},
  ],
  token1: [
    {required: true, message: t('message.ChainNameNotNull'), trigger: 'blur'},
  ],
  rate: [
    {required: true, message: t('message.FeeAddress'), trigger: 'blur'},
  ],

})


// 获取用户配置列表
async function getList() {
  try {
    loading.value = true
    const {code, data, msg} = await findChain()
    if (code === 200) {
      tableData.value = data.list
      total.value = data.total
    } else {
      ElMessage.error(msg)
    }
  } catch (error) {
    console.log(error)
  } finally {
    loading.value = false
  }
}


// 获取配置列表-链 方法
async function getChainConfigs() {
  const {code, data, msg} = await chainConfigs()
  if (code === 200) {
    chainList.value = data
  } else {
    ElMessage.error(msg)
  }
}



  // 获取用户配置-token 列表
async function getChainTokensFun(chainId){
  const {code, data, msg} = await chainTokens({
    chainConfigId: chainId
  })
  if (code === 200) {
    tokenList.value = data
  } else {
    ElMessage.error(msg)
  }
}


// 判断是否选择了相同的链
async function sameChain(chainConfigId0, chainConfigId1){
  if(!chainConfigId0 || !chainConfigId1){
    return
  }

  if(chainConfigId0 === chainConfigId1){
    ElMessage.warning(t('message.Redeem'))
    return false
  }else{
    return true
  }
}

// 重置表单
function resetForm() {
  form.chainConfigId0 = ''
  form.chainConfigId1 = ''
  form.token0 = ''
  form.token1 = ''
  form.rate = ''
}



// 分页
const handleSizeChange = (val) => {
  pageSize.value = val
  getList()
}

// 分页
const handleCurrentChange = (val) => {
  pageIndex.value = val
  getList()
}

</script>

<style scoped lang="less">
.generate {
  text-align: left;
  margin: 10px
}
.myTable{
  .title{
    margin:.2rem 0 ;
  }
}

.fee{
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: flex-start;
}
.coll{
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: flex-start;
  margin: .5rem 0;
}

.withdraw{
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: flex-start;
}


</style>